package com.example.yilanchatserver.application.controller;

import com.alibaba.fastjson.JSON;
import com.example.yilanchatserver.business.freechat.BusinessErrorCodes;
import com.example.yilanchatserver.business.freechat.BusinessException;
import com.example.yilanchatserver.business.freechat.service.ChatGPTService;
import com.example.yilanchatserver.business.freechat.service.FreeChatService;
import com.example.yilanchatserver.business.freechat.service.dto.FreeChatDTO;
import com.example.yilanchatserver.business.freechat.service.dto.FreeChatInputDTO;
import com.example.yilanchatserver.business.freechat.service.dto.FreeChatPromptDTO;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;

import javax.annotation.Resource;
import java.util.Objects;
import java.util.concurrent.CompletableFuture;

@RestController
@RequestMapping("/metah/freechat")
public class FreeChatController {
    @Resource
    private FreeChatService freeChatService;

    @Resource
    private ChatGPTService chatGPTService;

    @PostMapping("/get")
    public Object getFreeChat(@RequestBody FreeChatInputDTO freeChatDTO) throws Exception {
        String chosenService = freeChatDTO.getChosenService();
        if (Objects.equals(chosenService, "zhipu")) {
            if (freeChatDTO.getIsCustom()) {
                CompletableFuture future = freeChatService.getDataWithPrompt_v1(JSON.parseObject(JSON.toJSONString(freeChatDTO), FreeChatPromptDTO.class));
                return future.get();
            }
            CompletableFuture future = freeChatService.getData(JSON.parseObject(JSON.toJSONString(freeChatDTO), FreeChatDTO.class));
            return future.get();
        } else if (Objects.equals(chosenService, "chatGPT")) {
            CompletableFuture future = freeChatService.getChatGPT(JSON.parseObject(JSON.toJSONString(freeChatDTO), FreeChatDTO.class));
            return future.get();
        } else if (Objects.equals(chosenService, "ernieBot")) {
            // 百度文心一言
            CompletableFuture future = freeChatService.getErnieBotData(JSON.parseObject(JSON.toJSONString(freeChatDTO), FreeChatDTO.class));
            return future.get();
        } else {
            throw new BusinessException(BusinessErrorCodes.DATA_NOT_EXISTS);
        }
    }

    @PostMapping("/chatgpt")
    public void getGpt(@RequestBody FreeChatDTO freeChatDTO) {
        Flux<String> response = chatGPTService.send(freeChatDTO);
        response.subscribe(message -> {
            System.out.println(response);
        });
    }

    @PostMapping("/get/prompt")
    public Object getFreeChat(@RequestBody FreeChatPromptDTO freeChatDTO) throws Exception {
        CompletableFuture future = freeChatService.getDataWithPrompt(freeChatDTO);
        return future.get();
    }


}
